<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>平滑切换视频源</title>
  <style>
    .video-container {
      position: relative;
      width: 600px;
      height: 338px;
      overflow: hidden;
    }
    .video-container video {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      transition: opacity 1s ease;
    }
    .hidden {
      opacity: 0;
      pointer-events: none;
    }
    .visible {
      opacity: 1;
      pointer-events: auto;
    }
  </style>
</head>
<body>
  <div class="video-container">
    <!-- 当前正在播放的视频 -->
    <video id="currentVideo" class="visible" autoplay muted>
      <source src="./video/vidoe1.mp4" type="video/mp4">
      Your browser does not support the video tag.
    </video>
    <!-- 准备切换的视频 -->
    <video id="nextVideo" class="hidden" muted>
      <source src="" type="video/mp4">
      Your browser does not support the video tag.
    </video>
  </div>
  <button id="switchButton">切换视频</button>

  <script>
    // 获取 DOM 元素
    const currentVideo = document.getElementById('currentVideo');
    const nextVideo = document.getElementById('nextVideo');
    const switchButton = document.getElementById('switchButton');

    // 切换视频源函数
    function switchVideo(newSrc) {
      // 加载新的视频到 nextVideo
      nextVideo.src = newSrc;
      nextVideo.oncanplay = () => {
        // 播放新视频
        nextVideo.play();
        // 视频淡入淡出效果
        currentVideo.classList.replace('visible', 'hidden');
        nextVideo.classList.replace('hidden', 'visible');

        // 切换完成后，更新 currentVideo 的源
        setTimeout(() => {
          currentVideo.src = newSrc;
          currentVideo.classList.replace('hidden', 'visible');
          nextVideo.classList.replace('visible', 'hidden');
          nextVideo.pause(); // 停止 nextVideo 播放，释放资源
        }, 1000); // 与 CSS 的 transition 时间同步
      };
    }

    // 切换视频事件绑定
    switchButton.addEventListener('click', () => {
      const newVideoSrc = "./video/video2.mp4";
      switchVideo(newVideoSrc);
    });
  </script>
</body>
</html>
